//
//  ZNWBNewFeaturesView.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/21.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit

class ZNWBNewFeaturesView: UIView {
    fileprivate let pagesCount = 4
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterWeiBoButton: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    
    class func newFeaturesView() -> ZNWBNewFeaturesView {
        let nib = UINib(nibName: "ZNWBNewFeaturesView", bundle: nil)
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! ZNWBNewFeaturesView
        view.frame = UIScreen.main.bounds
        
        return view
    }
    @IBAction func touchEnterWeiBo(_ sender: UIButton) {
        removeFromSuperview()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        let rect = UIScreen.main.bounds
        
        // 添加新特性视图
        for i in 0..<pagesCount {
            let imageName = "new_feature_\(i + 1)"
            let imageView = UIImageView(image: UIImage(named: imageName))

            imageView.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(imageView)
        }
        
        // 设置内容尺寸，一页空白界面用于判断即将移除视图
        scrollView.contentSize = CGSize(width: CGFloat(pagesCount + 1) * rect.width, height: rect.height)

        scrollView.isPagingEnabled = true
        scrollView.bounces = false
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.delegate = self
        
        // 隐藏进入按钮
        enterWeiBoButton.isHidden = true
    }
}

extension ZNWBNewFeaturesView: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if page == pagesCount {
            removeFromSuperview()
        }
        
        enterWeiBoButton.isHidden = (page != pagesCount - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        enterWeiBoButton.isHidden = true
        
        // 加上0.5表示一页滚动一半时就选中下一页
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        // 设置页码
        pageControl.currentPage = page
        
        pageControl.isHidden = (page == pagesCount)
    }
}
